package com.amentretenimiento;

import java.net.URL;
import java.util.Calendar;
import java.util.List;
import java.util.Vector;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class TiendaPromotor extends ListActivity {
//	String urlamentretenimiento="http://201.155.80.190:8080/";
//	private String urlamentretenimiento="http://201.155.80.190:1863/";
	private String urlamentretenimiento=UsuariosSQLiteHelper.urlam;

//	String urlamentretenimiento="http://www.smartthinking.com.mx:8080/";


	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	private int posicion;

	int tiendas=0;
	UsuariosSQLiteHelper usdbh;
	SQLiteDatabase db;
	Bundle extras;
	SAXParserFactory spf;
	SAXParser sp;
	XMLReader xr ;
	int ruta;
	LoginSitesList loginsitesList = null;
	private LayoutInflater mInflater;
	private Vector<RowData> data;
	String idAgente, nombre;
	private String idcia;
	int dia;
	
	@Override
	public void onBackPressed() {
		boolean internet = isInternetConnectionActive(TiendaPromotor.this);
		if (internet == true){	
		
			Intent atras=new Intent(TiendaPromotor.this, EsSupervisor.class);
			atras.putExtra("nombre", nombre);
//			atras.putExtra("idagente", idAgente);
//			atras.putExtra("miusuario", miusuario);
			startActivity(atras);
			
		}else if(internet == false){
//			Toast.makeText(getApplicationContext(), "Necesitas conexión a internt", Toast.LENGTH_LONG).show();
            AlertDialog alertdialog=new AlertDialog.Builder(TiendaPromotor.this).create();
			alertdialog.setIcon(R.drawable.icon);
	    	alertdialog.setTitle("Aviso");
	    	alertdialog.setMessage("Error de conectividad");
	    	alertdialog.show();
		}
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		
		 SharedPreferences preferences = getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
		  SharedPreferences.Editor editor = preferences.edit();
		  editor.putInt("visitada", 0);
		  editor.commit();
		  Log.i("VALOR VISITADA PREFERENCIAS", ""+preferences.getInt("visitada", 0));
	}
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.superpromotor);
        usdbh =
                new UsuariosSQLiteHelper(this, "BaseItems", null, 1);
		Calendar cal=Calendar.getInstance();
		dia=cal.get(Calendar.DAY_OF_WEEK);
		if(dia==1){
			dia=7;
		}else{
			dia=(cal.get(Calendar.DAY_OF_WEEK)-1);
			
		}
		
		Bundle extras=getIntent().getExtras();
		if(extras!=null){
			

			mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
	        data = new Vector<RowData>();
			idcia=extras.getString("idcia");

	        nombre = extras.getString("nombre");
			idAgente=extras.getString("idagente");
			loginsitesList=mostrarInfor(idAgente);
			
			
			if(loginsitesList.getidCia().size()==0  && tiendas==0){
				stopService();
			     AlertDialog alertdialog=new AlertDialog.Builder(TiendaPromotor.this).create();
								alertdialog.setIcon(R.drawable.icon);
						    	alertdialog.setTitle("Aviso");
						    	alertdialog.setMessage("No existen tiendas");
						    	alertdialog.setButton("Aceptar	", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface arg0, int arg1) {
										
										finish();
									}
								});
								alertdialog.show();
						    	
			}else{
			
				
				TextView nom = (TextView) findViewById(R.id.nombrepro);
				SharedPreferences prefs =
					     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
				nom.setText(prefs.getString("nomagente", "nulo"));
//				nom.setText(nombre);
				for (int i = 0; i < loginsitesList.getnombre().size(); i++) {
	
					RowData rd = new RowData(""+loginsitesList.getnombre().get(i),""+loginsitesList.getidCliente().get(i) );
			        data.add(rd);
				}
				}
			CustomAdapter adapter = new CustomAdapter(this, R.layout.custom_row2,R.id.item, data);
	        setListAdapter(adapter);  
		}
		
	}
	
	private class RowData {
	    protected String mItem;
	        protected String mDescription;

	        RowData(String item, String description){
	        mItem = item;
	        mDescription = description;             
	    }

	        @Override
	        public String toString() {
	                return mItem + " " +  mDescription;
	        }
	}
	
	private class CustomAdapter extends ArrayAdapter<RowData> {

        public CustomAdapter(Context context, int resource,
                        int textViewResourceId, List<RowData> objects) {
                super(context, resource, textViewResourceId, objects);

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder = null;

                //widgets displayed by each item in your list
                TextView item = null;
                TextView description = null;

                //data from your adapter
                RowData rowData= getItem(position);


                //we want to reuse already constructed row views...
                if(null == convertView){
                        convertView = mInflater.inflate(R.layout.custom_row2, null);
                        holder = new ViewHolder(convertView);
                        convertView.setTag(holder);
                }
                // 
                holder = (ViewHolder) convertView.getTag();
                item = holder.getItem();
                item.setText(rowData.mItem);
                item.setTextSize(18);
//    			item.setTextColor(Color.BLACK);

                description = holder.getDescription();          
                description.setText(rowData.mDescription);
                description.setTextSize(16);
//    			description.setTextColor(Color.BLACK);

//                if(color(position)){
//	    			description.setTextColor(Color.RED);
//	    			item.setTextColor(Color.RED);
//                }else{
//	    			description.setTextColor(Color.BLACK);
//	    			item.setTextColor(Color.BLACK);
//                }
                SharedPreferences prefs =
					     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
                
                if((mostrarInfoEntradaSalida(prefs.getString("idagentesupervisor", "nulo"), loginsitesList.getidCliente().get(position), 'E'))&&
                		(mostrarInfoEntradaSalida(prefs.getString("idagentesupervisor", "nulo"), loginsitesList.getidCliente().get(position), 'S'))){
	    			description.setTextColor(Color.RED);
	    			item.setTextColor(Color.RED);
                }else if((mostrarInfoEntradaSalida(prefs.getString("idagentesupervisor", "nulo"), loginsitesList.getidCliente().get(position), 'E'))&&
                		(!(mostrarInfoEntradaSalida(prefs.getString("idagentesupervisor", "nulo"), loginsitesList.getidCliente().get(position), 'S')))){
                	description.setTextColor(Color.BLUE);
	    			item.setTextColor(Color.BLUE);
                }else{
	    			description.setTextColor(Color.BLACK);
	    			item.setTextColor(Color.BLACK);
                }
                
                
                
    			
                return convertView;
        }
}
	
	
	private class ViewHolder {      
	    private View mRow;
	    private TextView description = null;
	    private TextView item = null;

	        public ViewHolder(View row) {
	        mRow = row;
	        }

	        public TextView getDescription() {
	                if(null == description){
	                        description = (TextView) mRow.findViewById(R.id.item);
	                }
	                return description;
	        }

	        public TextView getItem() {
	                if(null == item){
	                        item = (TextView) mRow.findViewById(R.id.description);
	                }
	                return item;
	        }       
	}
	
	protected LoginSitesList mostrarInfor(String IdAgente) {
		LoginSitesList loginsitesList = null;

			
			try {
				
				/** Handling XML */
				spf = SAXParserFactory.newInstance();
				sp = spf.newSAXParser();
				xr = sp.getXMLReader();
	
	
				
				SharedPreferences prefs =
					     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);

				Log.i("DIA", ""+dia);
				
				/** Send URL to parse XML Tags */
				URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?Query=select*from+ruta+where+idagente="+prefs.getString("idpromotor", "nulo")+"and+dia="+dia);
				
				Log.i("TAGG", ""+sourceUrl);
	
				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
				xr.setContentHandler(myXMLHandler);
				xr.parse(new InputSource(sourceUrl.openStream()));
				
			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}
			loginsitesList = LoginMyXMLHandler.loginsitesList;
			
			if(loginsitesList.getidCia().size()==0){
				tiendas=1;
				stopService();
			     AlertDialog alertdialog=new AlertDialog.Builder(TiendaPromotor.this).create();
								alertdialog.setIcon(R.drawable.icon);
						    	alertdialog.setTitle("Aviso");
						    	alertdialog.setMessage("No existen rutas");
						  
						       	alertdialog.setButton("Aceptar	", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface arg0, int arg1) {
										finish();
									}
								});
						      	alertdialog.show();
						    	
			}else{
			
					
					
					
					Log.i("Nooooo", ""+loginsitesList.getIdRuta().get(0).toString());
					ruta= Integer.parseInt(loginsitesList.getIdRuta().get(0).toString()); 
					
					
					try {
						
						/** Handling XML */
						spf = SAXParserFactory.newInstance();
						sp = spf.newSAXParser();
						xr = sp.getXMLReader();
			
						/** Send URL to parse XML Tags */
						
						
						
						
						URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?Query=select+idcia,idruta,a.idcliente,b.numsucursal,b.nombre,secuencia,hora,ttranslado+from+itinerario+a+inner+join+cliente+b+on+a.idcliente=b.idcliente+where+idruta="+ruta+"order+by+secuencia");
						
						Log.i("MII TAGG", ""+sourceUrl);
			
						/** Create handler to handle XML Tags ( extends DefaultHandler ) */
						LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
						xr.setContentHandler(myXMLHandler);
						xr.parse(new InputSource(sourceUrl.openStream()));
						
					} catch (Exception e) {
						System.out.println("XML Pasing Excpetion = " + e);
					}
					loginsitesList = LoginMyXMLHandler.loginsitesList;
			

			}
		return loginsitesList;
		
		
	}
	
	public void onListItemClick(ListView parent, View v, int position, long id) {
		 SharedPreferences prefs =
			     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
		if((mostrarInfoEntradaSalida(prefs.getString("idagentesupervisor", "nulo"), loginsitesList.getidCliente().get(position), 'E'))&&
        		(mostrarInfoEntradaSalida(prefs.getString("idagentesupervisor", "nulo"), loginsitesList.getidCliente().get(position), 'S')))
		{
			Log.i("OPC1", "OPC1");
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage("Esta tienda ya se ha visitado")
				       .setCancelable(false)
				       .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
				           public void onClick(DialogInterface dialog, int id) {
				           	}
				       })
				      ;
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
		
		
		else if((mostrarInfoEntradaSalida(prefs.getString("idagentesupervisor", "nulo"), loginsitesList.getidCliente().get(position), 'E'))&&
            		(!(mostrarInfoEntradaSalida(prefs.getString("idagentesupervisor", "nulo"), loginsitesList.getidCliente().get(position), 'S')))){
			Log.i("OPC2", "OPC2");

	    
			
	        Intent nd = new Intent(TiendaPromotor.this, MenuSupervisor.class);
	        
   	        nd.putExtra("idcia", ""+idcia);  
   	        nd.putExtra("idagente", ""+idAgente);
   	        nd.putExtra("idcliente", ""+loginsitesList.getidCliente().get(position).toString().trim());
   	        nd.putExtra("numsucursal", ""+loginsitesList.getnumSucursal().get(position).toString().trim());
   	        nd.putExtra("visitada", 2);

   	     
   	     SharedPreferences.Editor editor=prefs.edit();
   	        editor.putString("nombre", ""+loginsitesList.getnombre().get(position).toString().trim());
   	        
   	        editor.commit();
	        
	        startActivity(nd);
			
			

			
			}else{
			
	    
				Log.i("OPC3", "OPC3");

	        Intent nd = new Intent(TiendaPromotor.this, MenuSupervisor.class);
	        
   	        nd.putExtra("idcia", ""+idcia);  
   	        nd.putExtra("idagente", ""+idAgente);
   	        nd.putExtra("idcliente", ""+loginsitesList.getidCliente().get(position).toString().trim());
   	        nd.putExtra("numsucursal", ""+loginsitesList.getnumSucursal().get(position).toString().trim());
   	        
   	        nd.putExtra("visitada", 0);

   	     SharedPreferences.Editor editor=prefs.edit();
   	        editor.putString("nombre", ""+loginsitesList.getnombre().get(position).toString().trim());
   	        
   	        editor.commit();
	        
	        startActivity(nd);

	        
			}
  
	}
	public static boolean isInternetConnectionActive(Context context) {
		 boolean bool = false;

		   NetworkInfo networkInfo = ((ConnectivityManager) context
                 .getSystemService(Context.CONNECTIVITY_SERVICE))
                 .getActiveNetworkInfo();

               if(networkInfo == null || !networkInfo.isConnected()) {
                return false;
               }
               return true;
	}
	
    private void stopService() {
    	Intent svc = new Intent(this, SystemService.class);
		stopService(svc);
    }
    
	protected boolean mostrarInfoEntradaSalida(String IdAgente, String idcliente, char proceso) {
		LoginSitesList loginsitesList = null;
		boolean bool = false;

			try {
				
				/** Handling XML */
				spf = SAXParserFactory.newInstance();
				sp = spf.newSAXParser();
				xr = sp.getXMLReader();
	
				/****CAMBIAR 2 POR VARIABLE DIA****/
				
				/** Send URL to parse XML Tags */
				URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?" +
						"Query=select+count(*)+as+totalvisitada+from+gps+where+convert(varchar,fecha,111)+" +
						"=convert(varchar,getdate(),111)and+IdAgente+="+IdAgente+"+and+idCliente="+idcliente+"+and+proceso='"+proceso+"'");
				
				Log.i("MII TAGG ENTRADA SALIDA", ""+sourceUrl);
	
				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
				xr.setContentHandler(myXMLHandler);
				xr.parse(new InputSource(sourceUrl.openStream()));
				
			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}
			loginsitesList = LoginMyXMLHandler.loginsitesList;	
			
			Log.i("TOTAL TOTAL TOTAL", loginsitesList.getTotalVisitada().get(0));
			if(loginsitesList.getTotalVisitada().get(0).equals("1")){
				bool = true;
			}else if(loginsitesList.getTotalVisitada().get(0).equals("0")){
				bool = false;
			}
			
			
		return bool;
		
	}
    
    
    
//	public boolean color(int pos) {
//		Calendar calbase;
//		String fecha=null;
//		 int dia,mes, year;
//		 calbase=Calendar.getInstance();
//		 dia=calbase.get(Calendar.DAY_OF_MONTH);
//		 mes=(calbase.get(Calendar.MONTH))+1;
//		 year=calbase.get(Calendar.YEAR);
//		 
//		 if(mes<10 && dia<10){
//				fecha=year+"-0"+mes+"-0"+dia;
//
//		 }
//		 if(dia<10 && mes>=10){
//				fecha=year+"-"+mes+"-0"+dia;
//
//		 }
//		 if(mes<10 && dia>=10){
//				fecha=year+"-0"+mes+"-"+dia;
//
//		 }
//		 
//		//Log.i("FECHA", ""+fecha);
//		boolean var=false;
//		db = usdbh.getWritableDatabase();
//	    if(db != null)
//	    {
//				 posicion=pos;
//				 SharedPreferences prefs =
//					     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
//				 
//				 String[] argse = new String[] { ""+loginsitesList.getnombre().get(posicion).toString().trim(),
//						 fecha,prefs.getString("idagente", "nulo"),prefs.getString("idpromotor", "nulo")};
//				 Cursor c = db.rawQuery(" SELECT * FROM ItemsSup WHERE " +
//				 		"ntienda=? AND fecha=? AND idsupervisor=? AND idagente=?", argse);
//				 
//				 
////				 String[] argse = new String[] {""+pos,fecha, idAgente};
//////				 Log.i("args", ""+pos+" "+fecha);
////				 Cursor c = db.rawQuery(" SELECT * FROM Items WHERE item=? AND fecha=? AND idagente=?", argse);
//					if (c.moveToFirst()) {
//							var=true;
//
//					}else{
//							var=false;
//					}
//	        db.close();    
//	    }
//		return var;				
//	}

}
